package thread;

public class SyncDemo {
    private static boolean accsee1 = false;
    private static boolean accsee2 = false;
    public static void main(String[] args) {
        Bank bank = new Bank();
        int i = 1;
        while (true){
            Thread t1 = new Thread(){
                public void run(){
                    accsee1 = bank.getMoney(20000);
                }
            };
            Thread t2 = new Thread(){
                public void run(){
                    accsee2 = bank.getMoney(20000);
                }
            };
            t1.start();
            t2.start();
            try {
                Thread.sleep(20);
            }catch (InterruptedException e){
            }
            if (accsee1 & accsee2){
                System.out.println("卡BUG成功！同时取到钱");
                break;
            }else {
                System.out.println("卡BUG失败！只有一个人取到了钱");
                bank.setAccount(20000);
                accsee1 = false;
                accsee2 = false;
            }
            i++;
        }
        System.out.println("一共卡了" + i + "次BUG才从从银行骗取到钱");
    }
}

class Bank{
    private int account = 20000;
    public synchronized boolean getMoney(int money){
        int account = getAccount();
        if(account >= money){
            account -= money;
            Thread.yield();  //
//            try {
//                Thread.sleep(10);
//            }catch (InterruptedException e){
//            }
            setAccount(account);
            return true;
        }
        return false;
    }
    public int getAccount(){
        return account;
    }
    public void setAccount(int account){
        this.account = account;
    }
}